/** index.js By Beginner Emain:zheng_jinfan@126.com HomePage:http://www.zhengjinfan.cn */

var tab;

layui.config({
	base: 'js/',
	version:new Date().getTime()
}).use(['element', 'layer', 'navbar', 'tab'], function() {
	var element = layui.element(),
		$ = layui.jquery,
		layer = layui.layer,
		navbar = layui.navbar();
		tab = layui.tab({
			elem: '.admin-nav-card' //设置选项卡容器
				,
			//maxSetting: {
			//	max: 5,
			//	tipMsg: '只能开5个哇，不能再开了。真的。'
			//},
			contextMenu:true
		});
	//iframe自适应
	$(window).on('resize', function() {
		var $content = $('.admin-nav-card .layui-tab-content');
		$content.height($(this).height() - 147);
		$content.find('iframe').each(function() {
			$(this).height($content.height());
		});
	}).resize();

	//设置navbar
	navbar.set({
		spreadOne: true,
		elem: '#admin-navbar-side',
		cached: true/*,
		data: navs*/
		/*cached:true,
		url: 'datas/nav.json'*/
	});
	/*//渲染navbar
	navbar.render();
	//监听点击事件
	navbar.on('click(side)', function(data) {
		tab.tabAdd(data.field);
	});*/

	$('.admin-side-toggle').on('click', function() {
		var sideWidth = $('#admin-side').width();
		if(sideWidth === 200) {
			$('#admin-body').animate({
				left: '0'
			}); //admin-footer
			$('#admin-footer').animate({
				left: '0'
			});
			$('#admin-side').animate({
				width: '0'
			});
		} else {
			$('#admin-body').animate({
				left: '200px'
			});
			$('#admin-footer').animate({
				left: '200px'
			});
			$('#admin-side').animate({
				width: '200px'
			});
		}
	});
	$('.admin-side-full').on('click', function() {
		var docElm = document.documentElement;
		//W3C  
		if(docElm.requestFullscreen) {
			docElm.requestFullscreen();
		}
		//FireFox  
		else if(docElm.mozRequestFullScreen) {
			docElm.mozRequestFullScreen();
		}
		//Chrome等  
		else if(docElm.webkitRequestFullScreen) {
			docElm.webkitRequestFullScreen();
		}
		//IE11
		else if(elem.msRequestFullscreen) {
			elem.msRequestFullscreen();
		}
		layer.msg('按Esc即可退出全屏');
	});
	
	

	//锁屏
	$(document).on('keydown', function() {
		var e = window.event;
		if(e.keyCode === 76 && e.altKey) {
			//alert("你按下了alt+l");
			lock($, layer);
		}
	});
	$('#lock').on('click', function() {
		lock($, layer);
	});

	//手机设备的简单适配
	var treeMobile = $('.site-tree-mobile'),
		shadeMobile = $('.site-mobile-shade');
	treeMobile.on('click', function() {
		$('body').addClass('site-mobile');
	});
	shadeMobile.on('click', function() {
		$('body').removeClass('site-mobile');
	});
});

var isShowLock = false;
function lock($, layer) {
	if(isShowLock)
		return;
	//自定页
	layer.open({
		title: false,
		type: 1,
		closeBtn: 0,
		anim: 6,
		content: $('#lock-temp').html(),
		shade: [0.9, '#393D49'],
		success: function(layero, lockIndex) {
			isShowLock = true;
			//给显示用户名赋值
			layero.find('div#lockUserName').text('admin');
			layero.find('input[name=lockPwd]').on('focus', function() {
					var $this = $(this);
					if($this.val() === '输入密码解锁..') {
						$this.val('').attr('type', 'password');
					}
				})
				.on('blur', function() {
					var $this = $(this);
					if($this.val() === '' || $this.length === 0) {
						$this.attr('type', 'text').val('输入密码解锁..');
					}
				});
			//在此处可以写一个请求到服务端删除相关身份认证，因为考虑到如果浏览器被强制刷新的时候，身份验证还存在的情况			
			//do something...
			//e.g. 
			/*
			 $.post(url,params,callback,'json');
			 */
			//绑定解锁按钮的点击事件
			layero.find('button#unlock').on('click', function() {
				var $lockBox = $('div#lock-box');

				var userName = $lockBox.find('div#lockUserName').text();
				var pwd = $lockBox.find('input[name=lockPwd]').val();
				if(pwd === '输入密码解锁..' || pwd.length === 0) {
					layer.msg('请输入密码..', {
						icon: 2,
						time: 1000
					});
					return;
				}
				unlock(userName, pwd);
			});
			/**
			 * 解锁操作方法
			 * @param {String} 用户名
			 * @param {String} 密码
			 */
			var unlock = function(un, pwd) {
				//这里可以使用ajax方法解锁
				/*$.post('api/xx',{username:un,password:pwd},function(data){
				 	//验证成功
					if(data.success){
						//关闭锁屏层
						layer.close(lockIndex);
					}else{
						layer.msg('密码输入错误..',{icon:2,time:1000});
					}					
				},'json');
				*/
				isShowLock = false;
				//演示：默认输入密码都算成功
				//关闭锁屏层
				layer.close(lockIndex);
			};
		}
	});
};
function index() {
	var header = '<div class="layui-main"> \
        <div class="admin-login-box">\
        <div style="left: 0;width: 300px;line-height: 60px">\
        <span style="font-size: 22px;color: #009688;" >后台管理平台&nbsp;<small style="font-family: 黑体">_随手快递<span class="fa fa-gift"></span></small></span>\
        </div>\
        </div>\
        <ul class="layui-nav admin-header-item">\
        <li class="layui-nav-item">\
        <a href="javascript:;" class="admin-header-user">\
        <img id="managerImg" src="../../images/0.jpg" />\
        <span id="managerName">beginner</span>\
        </a>\
        <dl class="layui-nav-child">\
        <dd>\
        <a href="../setting/personinfo.html"><i class="fa fa-user-circle" aria-hidden="true"></i> 个人信息</a>\
        </dd>\
        <dd>\
        <a href="../setting/editpersoninfo.html"><i class="fa fa-gear" aria-hidden="true"></i> 设置</a>\
        </dd>\
        <dd>\
        <a href="../login.html" onclick="adminRemovecookie()"><i class="fa fa-sign-out" aria-hidden="true"></i> 注销</a>\
        </dd>\
        </dl>\
        </li>\
        </ul>\
        <ul class="layui-nav admin-header-item-mobile">\
        <li class="layui-nav-item">\
        <a href="login.html"><i class="fa fa-sign-out" aria-hidden="true"></i> 注销</a>\
        </li>\
        </ul>\
        </div>';

	$(".layui-header").html(header);

	var leftnav = '<div class="layui-side-scroll" id="admin-navbar-side" lay-filter="side">' +
		'<ul class="layui-nav layui-nav-tree beg-navbar">' +
		'<li class="layui-nav-item" id="datareport"><a href="../statisticalReport/datareport.html" ><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>首页</cite></a></li>' +

		'<li class="layui-nav-item" id="account"><a href="javascript:;">' +
		'<i class="fa fa-cubes" aria-hidden="true" data-icon="fa-cubes"></i><cite>账号管理</cite><span class="layui-nav-more"></span></a>' +
		'<dl class="layui-nav-child">' +
		'<dd id="user"><a href="../accountManage/users.html"><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>用户管理</cite></a></dd>' +
		'<dd id="express"><a href="../accountManage/express.html"><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>快递员管理</cite></a></dd>' +
		'<dd id="expressapproval"><a href="../accountManage/expressapproval.html" ><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>快递员审批</cite></a></dd>' +
		'<dd id="manager"><a href="../accountManage/manager.html"><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>管理员管理</cite></a></dd>' +
		'</dl>' +
		'</li>' +
		'<li class="layui-nav-item" id="order"><a href="../orderManage/order.html" ><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>订单管理</cite></a></li>' +
		'<li class="layui-nav-item" id="complain"><a href="../complainManage/complain.html" ><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>投诉处理</cite></a></li>' +
		'<li class="layui-nav-item" id="fund"><a href="../fundManage/fund.html" ><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>资金管理</cite></a></li>' +
		'<li class="layui-nav-item" id="voucher"><a href="../voucherManage/voucher.html" ><i class="fa fa-stop-circle" aria-hidden="true" data-icon="fa-stop-circle"></i><cite>代金券管理</cite></a></li>' +
		'<span class="layui-nav-bar" style="top: 337.5px; height: 0px; opacity: 0;"></span></ul></div>'

	$("#admin-side").html(leftnav);

	var footer = '<div class="layui-main">\
					<p>2016 &copy;\
						<a href="http://m.zhengjinfan.cn/">m.zhengjinfan.cn/</a> LGPL license\
					</p>\
				</div>';
	$("#admin-footer").html(footer);
}
$(function(){
    index();
})

function getAllNodes(_id)
{
	return $(_id).dataTable().fnGetNodes();
}

/* select全选和全部取消*/
function checkAll(obj, tableid){
	var flag = obj.checked;
	var allNodes = getAllNodes(tableid);
	for (var tr in allNodes)
	{
		checkbox = allNodes[tr]["cells"][0]["childNodes"][0];
		if(checkbox!=null){
			if(checkbox["checked"] != flag){
				checkbox["checked"] = flag;
			}
		}
	}
}


/*function setCookie(c_name, value, expiredays) {
	var exdate = new Date()
	exdate.setDate(exdate.getDate() + expiredays)
	document.cookie = c_name + "=" + escape(value) +
		((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) +"; path=/"
}
//获取cookie  
//
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

//清除cookie    
function clearCookie(name) {
	setCookie(name, "", -1);
}*/


function adminCookie(){
	$("#managerName").text($.cookie("adminNickname"));
	$("#managerImg").attr('src',$.cookie("adminUrl")); 
}
function adminRemovecookie(){
$.removeCookie('adminNickname', { path: '/' });
$.removeCookie('adminUrl', { path: '/' });
$.removeCookie('adminId', { path: '/' });
}



Date.prototype.Format = function(fmt) { //author: meizz 
				var o = {
					"M+": this.getMonth() + 1, //月份 
					"d+": this.getDate(), //日 
					"h+": this.getHours(), //小时 
					"m+": this.getMinutes(), //分 
					"s+": this.getSeconds(), //秒 
					"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
					"S": this.getMilliseconds() //毫秒 
				};
				if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				for (var k in o)
					if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				return fmt;
			}



//金额格式化  不能和滚动相结合
function formatCurrency(num) 
        {
            if(num)
            {
                //将num中的$,去掉，将num变成一个纯粹的数据格式字符串
                num = num.toString().replace(/\$|\,/g,'');
                //如果num不是数字，则将num置0，并返回
                if(''==num || isNaN(num)){return 'Not a Number ! ';}
                //如果num是负数，则获取她的符号
                var sign = num.indexOf("-")> 0 ? '-' : '';
                //如果存在小数点，则获取数字的小数部分
                var cents = num.indexOf(".")> 0 ? num.substr(num.indexOf(".")) : '';
                cents = cents.length>1 ? cents : '' ;//注意：这里如果是使用change方法不断的调用，小数是输入不了的
                //获取数字的整数数部分
                num = num.indexOf(".")>0 ? num.substring(0,(num.indexOf("."))) : num ;
                //如果没有小数点，整数部分不能以0开头
                if('' == cents){ if(num.length>1 && '0' == num.substr(0,1)){return 'Not a Number ! ';}}
                //如果有小数点，且整数的部分的长度大于1，则整数部分不能以0开头
                else{if(num.length>1 && '0' == num.substr(0,1)){return 'Not a Number ! ';}}
                //针对整数部分进行格式化处理，这是此方法的核心，也是稍难理解的一个地方，逆向的来思考或者采用简单的事例来实现就容易多了
                /*
                  也可以这样想象，现在有一串数字字符串在你面前，如果让你给他家千分位的逗号的话，你是怎么来思考和操作的?
                  字符串长度为0/1/2/3时都不用添加
                  字符串长度大于3的时候，从右往左数，有三位字符就加一个逗号，然后继续往前数，直到不到往前数少于三位字符为止
                 */
                for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
                {
                    num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
                }
                //将数据（符号、整数部分、小数部分）整体组合返回
                return (sign + num + cents);    
            }

        }
